package com.zjdiepu.www.manage.api.system;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.zjdiepu.www.base.BaseController;
import com.zjdiepu.www.base.annotation.Add;
import com.zjdiepu.www.base.annotation.Update;
import com.zjdiepu.www.base.core.AbstractSysUser;
import com.zjdiepu.www.base.core.ApiResponse;
import com.zjdiepu.www.base.core.BaseException;
import com.zjdiepu.www.base.core.PageVo;
import com.zjdiepu.www.base.enums.status.DpStatus;
import com.zjdiepu.www.base.enums.type.CodeType;
import com.zjdiepu.www.base.enums.type.OperateType;
import com.zjdiepu.www.base.enums.type.ResultFlagType;
import com.zjdiepu.www.common.util.CollectionInitUtil;
import com.zjdiepu.www.ibiz.base.IBaseSalersmanOrgService;
import com.zjdiepu.www.ibiz.base.ISerialNumberService;
import com.zjdiepu.www.ibiz.system.IBaseBusiUnitService;
import com.zjdiepu.www.ibiz.system.IBaseCustomerService;
import com.zjdiepu.www.ibiz.system.IBaseSalersmanService;
import com.zjdiepu.www.ibiz.yw.IYwBusinessService;
import com.zjdiepu.www.model.base.dto.BaseSalersmanOrg;
import com.zjdiepu.www.model.system.dto.BaseBusiUnit;
import com.zjdiepu.www.model.system.dto.BaseCustomer;
import com.zjdiepu.www.model.system.dto.BaseSalersman;
import com.zjdiepu.www.model.system.ext.BaseCustomerExt;
import com.zjdiepu.www.model.system.ext.BaseSalersmanExt;
import com.zjdiepu.www.model.yw.dto.YwBusiness;
import com.zjdiepu.www.model.yw.ext.YwBusinessExt;

/**
 * Controller层<br/>
 * @author xiongxiaotun<br/>
 * @time 2017年05月18日 15时43分<br/>
 * @since 1.0<br/>
 */
@RestController
@RequestMapping(value= "BaseSalersmanController", produces="application/json;charset=UTF-8")
@Api(tags = {""}, produces="application/json;charset=UTF-8")
public class BaseSalersmanController extends BaseController {
    @Resource
    private IBaseSalersmanService baseSalersmanService;
    @Resource
    private IBaseBusiUnitService baseBusiUnitService;
    @Resource
	private ISerialNumberService serialNumberService;
    @Resource
    private IBaseCustomerService baseCustomerService;
    @Resource
    private IBaseSalersmanOrgService baseSalersmanOrgService;
    @Resource
    private IYwBusinessService ywBusinessService;

    /**
     * @author xiongxiaotun <br/>
     * @Title: save  <br/>
     * @Description: 新增 <br/>
     * @param baseSalersman
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "新增", response = Boolean.class, httpMethod="POST", tags={"新增"})
    @RequestMapping(value = "save", method = RequestMethod.POST)
    public ApiResponse save(@Validated(Add.class) @ModelAttribute BaseSalersman baseSalersman) {
    	AbstractSysUser currentUser = getCurrentUser();
    	baseSalersman.setModifier(currentUser.getId()); //统一使用修改人和修改人名称来初始化
    	baseSalersman.setModifierName(currentUser.getName());
    	baseSalersman.setSalersmanCode(getSalersmanCode(baseSalersman));
        baseSalersmanService.saveUpdateAndDelete(baseSalersman, OperateType.add);
        return ApiResponse.success(true);
    }
    @ApiOperation(value = "新增-判断是否重名", response = Boolean.class, httpMethod="POST", tags={"新增"})
    @RequestMapping(value = "insert", method = RequestMethod.POST)
    public ApiResponse insert(@Validated(Add.class) @ModelAttribute BaseSalersman baseSalersman) {
    	BaseSalersman bb=checkSalersman(baseSalersman);
    	if(bb!=null){
    		 return ApiResponse.fail(ResultFlagType.DATA_REPEAT.getCode(),ResultFlagType.DATA_REPEAT.getValue());
    	}
    	
    	AbstractSysUser currentUser = getCurrentUser();
    	baseSalersman.setModifier(currentUser.getId()); //统一使用修改人和修改人名称来初始化
    	baseSalersman.setModifierName(currentUser.getName());
    	baseSalersman.setSalersmanCode(getSalersmanCode(baseSalersman));
        baseSalersmanService.saveUpdateAndDelete(baseSalersman, OperateType.add);
        return ApiResponse.success(true);
    }
    private BaseSalersman checkSalersman(BaseSalersman baseSalersman) {
    	String name=baseSalersman.getName();
    	BaseSalersman baseSalersmans= new BaseSalersman();
    	baseSalersmans.setName(name);
    	baseSalersmans.setUnitId(baseSalersman.getUnitId());
    	baseSalersmans.setDpStatus(1);
    	BaseSalersman bb=baseSalersmanService.selectRefined(baseSalersmans);
		return bb;
	}
	/**
     * @author xiongxiaotun <br/>
     * @Title: remove  <br/>
     * @Description: 删除<br/>
     * @param id
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "删除", response = Boolean.class, httpMethod="POST", tags={"删除"})
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "数据主键", paramType="query", required = true, example="1")
    })
    @RequestMapping(value = "remove", method = RequestMethod.POST)
    public ApiResponse remove(String id) {
    	if(StringUtils.isBlank(id)) {
    		return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
    	}
    	AbstractSysUser currentUser = getCurrentUser();
    	List<String> ids = Arrays.asList(id.split(","));
    	baseSalersmanService.updateBatch(currentUser.getId(), currentUser.getName(), DpStatus.DELETED.getCode(), ids);
        return ApiResponse.success(true);
    }
    
    /**
     * @author xiongxiaotun <br/>
     * @Title: disable  <br/>
     * @Description: 禁用<br/>
     * @param id
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "禁用", response = Boolean.class, httpMethod="POST", tags={"禁用"})
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "数据主键", paramType="query", required = true, example="1")
    })
    @RequestMapping(value = "disable", method = RequestMethod.POST)
    public ApiResponse disable(String id) {
    	if(StringUtils.isBlank(id)) {
    		return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
    	}
    	AbstractSysUser currentUser = getCurrentUser();
    	List<String> ids = Arrays.asList(id.split(","));
    	baseSalersmanService.updateBatch(currentUser.getId(), currentUser.getName(), DpStatus.INVALID.getCode(), ids);
        return ApiResponse.success(true);
    }
    
    /**
     * @author xiongxiaotun <br/>
     * @Title: enable <br/>
     * @Description: 启用<br/>
     * @param id
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "启用", response = Boolean.class, httpMethod="POST", tags={"启用"})
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "数据主键", paramType="query", required = true, example="1")
    })
    @RequestMapping(value = "enable", method = RequestMethod.POST)
    public ApiResponse enable(String id) {
    	if(StringUtils.isBlank(id)) {
    		return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
    	}
    	AbstractSysUser currentUser = getCurrentUser();
    	List<String> ids = Arrays.asList(id.split(","));
    	baseSalersmanService.updateBatch(currentUser.getId(), currentUser.getName(), DpStatus.NORMAL.getCode(), ids);
        return ApiResponse.success(true);
    }

    /**
     * @author xiongxiaotun <br/>
     * @Title: modify  <br/>
     * @Description: 修改 <br/>
     * @param baseSalersman
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "修改", response = Boolean.class, httpMethod="POST", tags={"修改"})
    @RequestMapping(value = "modify", method = RequestMethod.POST)
    public ApiResponse modify(@Validated(Update.class) @ModelAttribute BaseSalersman baseSalersman) {
    	AbstractSysUser currentUser = getCurrentUser();
    	baseSalersman.setModifier(currentUser.getId()); //统一使用修改人和修改人名称来初始化
    	baseSalersman.setModifierName(currentUser.getName());
    	baseSalersmanService.saveUpdateAndDelete(baseSalersman, OperateType.edit);
        return ApiResponse.success(true);
    }
    
    @ApiOperation(value = "修改-判断是否重复", response = Boolean.class, httpMethod="POST", tags={"修改"})
    @RequestMapping(value = "doModify", method = RequestMethod.POST)
    public ApiResponse doModify(@Validated(Update.class) @ModelAttribute BaseSalersman baseSalersman) {
    	BaseSalersman bb=checkSalersman(baseSalersman);
    	if(bb!=null){
    		 return ApiResponse.fail(ResultFlagType.DATA_REPEAT.getCode(),ResultFlagType.DATA_REPEAT.getValue());
    	}
    	
    	AbstractSysUser currentUser = getCurrentUser();
    	baseSalersman.setModifier(currentUser.getId()); //统一使用修改人和修改人名称来初始化
    	baseSalersman.setModifierName(currentUser.getName());
    	baseSalersmanService.saveUpdateAndDelete(baseSalersman, OperateType.edit);
        return ApiResponse.success(true);
    }
    
    @ApiOperation(value = "修改业务员机构", response = Boolean.class, httpMethod="POST", tags={"修改"})
    @RequestMapping(value = "update", method = RequestMethod.POST)
    public ApiResponse update(@Validated(Update.class) @ModelAttribute BaseSalersman baseSalersman) {
    	AbstractSysUser currentUser = getCurrentUser();
    	String cruuentUserId=currentUser.getId();
    	String currentUserName=currentUser.getName();
    	baseSalersman.setModifier(cruuentUserId); //统一使用修改人和修改人名称来初始化
    	baseSalersman.setModifierName(currentUserName);
    	String salersManCode=getSalersmanCode(baseSalersman);
    	baseSalersman.setSalersmanCode(salersManCode);
    	baseSalersmanService.saveUpdateAndDelete(baseSalersman, OperateType.edit);
    	
    	BaseCustomerExt baseCustomerExt= new BaseCustomerExt();
    	baseCustomerExt.setSalesmanId(baseSalersman.getId());
    	List<BaseCustomer> list=baseCustomerService.selectByExt(baseCustomerExt);
    	if(list ==null || list.size()==0){
    		throw new BaseException(ResultFlagType.MISSING.getCode().toString(),ResultFlagType.MISSING.getValue());
    	}
    	//保存客户表中的业务编码
    	for (BaseCustomer baseCustomer : list) {
    		baseCustomer.setModified((int)(System.currentTimeMillis() / 1000));
    		baseCustomer.setModifier(cruuentUserId);
    		baseCustomer.setModifierName(currentUserName);
    		baseCustomer.setSalesmanCode(salersManCode);
    		baseCustomerService.updateByPrimaryKeySelective(baseCustomer);
		}
    	
    	//2018-01-24修改订单业务员
    	String salesmanId = baseSalersman.getId();
    	YwBusiness ywBusiness = new YwBusiness();
    	ywBusiness.setSalesmanId(salesmanId);
    	ywBusiness.setSalesmanCode(salersManCode);
    	
    	YwBusinessExt ywBusinessExt = new YwBusinessExt();
    	ywBusinessExt.setSalesmanId(salesmanId);
    	ywBusinessService.updateByExt(ywBusiness, ywBusinessExt);
    	
    	//插入业务员原来的机构信息
    	BaseSalersmanOrg baseSalersmanOrg=new BaseSalersmanOrg();
    	baseSalersmanOrg.setModifier(cruuentUserId);
    	baseSalersmanOrg.setModifierName(currentUserName);
    	baseSalersmanOrg.setOldUnitCode(baseSalersman.getOldUnitCode());
    	baseSalersmanOrg.setOldUnitId(baseSalersman.getOldUnitId());
    	baseSalersmanOrg.setOldUnitName(baseSalersman.getOldUnitName());
    	baseSalersmanOrg.setNewUnitCode(baseSalersman.getUnitCode());
    	baseSalersmanOrg.setNewUnitId(baseSalersman.getUnitId());
    	baseSalersmanOrg.setNewUnitName(baseSalersman.getOrgName());
    	baseSalersmanOrg.setSalersmanCode(baseSalersman.getSalersmanCode());
    	baseSalersmanOrg.setSalersmanName(baseSalersman.getName());
    	baseSalersmanOrg.setSalersmanId(baseSalersman.getId());
    	baseSalersmanOrgService.saveUpdateAndDelete(baseSalersmanOrg, OperateType.add);
        return ApiResponse.success(true);
    }

    /**
     * @author xiongxiaotun <br/>
     * @Title: getById  <br/>
     * @Description: 主键查询<br/>
     * @param id
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "主键查询", response = BaseSalersman.class, httpMethod="POST", tags={"主键查询"})
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "数据主键", paramType="query", required = true, example="1")
    })
    @RequestMapping(value = "getById", method = RequestMethod.POST)
    public ApiResponse getById(String id){
    	if(StringUtils.isBlank(id)) {
    		return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
    	}
       BaseSalersman baseSalersman = baseSalersmanService.selectById(id);
       if(null == baseSalersman) {
    	   return ApiResponse.fail(ResultFlagType.MISSING);
       }
       return ApiResponse.success(baseSalersman);
    }
    
    /**
     * @author xiongxiaotun <br/>
     * @Title: list  <br/>
     * @Description: 条件查询 <br/>
     * @param baseSalersmanExt
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "条件查询",response = BaseSalersman.class, httpMethod="POST", tags={"列表"})
    @RequestMapping(value = "list", method = RequestMethod.POST)
    public ApiResponse list(@ModelAttribute BaseSalersmanExt baseSalersmanExt){
        baseSalersmanExt.notDeleted();
        PageVo page = getPage(baseSalersmanExt);
        int records = baseSalersmanService.countByExt(baseSalersmanExt);
        page.setRecords(records);
        if (records > 0) {
            List<BaseSalersman> baseSalersmans = baseSalersmanService.selectByExt(baseSalersmanExt);
            for(BaseSalersman baseSalersman : baseSalersmans) {
            	String unitId = baseSalersman.getUnitId();
            	if(StringUtils.isNotBlank(unitId)){
            		BaseBusiUnit baseBusiUnit = baseBusiUnitService.selectById(unitId);
            		baseSalersman.setOrgName(baseBusiUnit.getOrgName());
            	}
            }
            page.setRows(baseSalersmans);
        } else {
            page.setRows(CollectionInitUtil.emptyList());
        }
        return ApiResponse.success(page);
    }
    /**
     * @author zhangzhengjian <br/>
     * @Title: list  <br/>
     * @Description: 多表查询 <br/>
     * @param baseSalersmanExt
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "多表查询",response = BaseSalersman.class, httpMethod="POST", tags={"列表"})
    @RequestMapping(value = "selectMuiltList", method = RequestMethod.POST)
    public ApiResponse selectMuiltList(@ModelAttribute BaseSalersmanExt baseSalersmanExt){
        baseSalersmanExt.notDeleted();
        PageVo page = getPage(baseSalersmanExt);
        int records = baseSalersmanService.countMuiltList(baseSalersmanExt);
        page.setRecords(records);
        if (records > 0) {
            List<BaseSalersman> baseSalersmans = baseSalersmanService.selectMuiltList(baseSalersmanExt);
            page.setRows(baseSalersmans);
        } else {
            page.setRows(CollectionInitUtil.emptyList());
        }
        return ApiResponse.success(page);
    }
    private String getSalersmanCode(BaseSalersman saleman){
		int sNumber=serialNumberService.createSerialNumber(CodeType.SALERSMAN, saleman.getUnitCode(), false);
		return saleman.getUnitCode() + new DecimalFormat("0000").format(sNumber);
	}
}
